// subpkg/goodsBuy/goodsBuy.js
//加载utils
const utils = require('../../utils/utils')
//调用数据库
const db = wx.cloud.database()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: '', //存放传参过来的商品id
        goodsMess: {}, //存放数据库获取的所有商品信息
        momey: 0, //存放商品原始金额
        num: 1, //存放商品库存量
        total: 1, //存放购买数量
        price: 0, //存放商品总价
        status: '', //存放商品状态
        isShow: false, // 支付框的显隐
        minusStatus: 'disable', //加减号按钮状态
        remark: '', //存放买家备注信息
        scrollHeight: 0,
        orderTime: '',     //存储订单支付时间
        createTime: '',    //存储订单创建时间
        orderId: '',       //存储订单id
        address: '',
        hasAddress: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {},
    /**
     * 获取商品信息
     */
    getGoodsMess() {
        //获取数据库
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'getIdlemallById',
                reqData: this.data.id
            }
        }).then(res => {
            // console.log('get goods by id success ==>', res);
            this.setData({
                goodsMess: res.result.resData,
                momey: res.result.resData.goodsData.goodsPrice,//商品价格
                num: res.result.resData.goodsData.goodsNum,//商品库存量
                status: res.result.resData.goodsStatus,//商品状态
                price: res.result.resData.goodsData.goodsPrice//商品价格--计算购买总价
            });
        }, err => {
            console.log('get goods by id error ==>', err);
        });
    },
    /**
     * 选择地址
     */
    onSelectAddress() {
        if(this.data.isNotLogin) {
            this.$showMsg('登录后可使用功能');
        }else {
            // 选择地址
            wx.navigateTo({
                url: '/pages/address_administration/address_administration',
            }).then(res => {
                console.log('address to new res ==> ', res);
            }, err => {
                console.log('address to new err ==> ', err);
            });
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getScrollHeight();
        let id = wx.getStorageSync('idlemallID');
        let address = wx.getStorageSync('idlemallAddress');
        if(address) {
            this.setData({
                hasAddress: true,
                address: address,
                id: id
            });
        }else {
            this.setData({
                id: id
            });
        }
        this.getGoodsMess();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    /**
     * 计算商品总价
     */
    priceTotal: function () {
        let total = this.data.total
        let money = this.data.momey
        let sum = total * money
        this.setData({
            price: sum
        });
    },
    /**
     * 库存加减框处理事件函数
     */
    /*点击减号*/
    bindMinus: function () {
        let total = this.data.total;
        if (total > 1) {
            total--;
        }
        let minusStatus = total > 1 ? 'normal' : 'disable';
        this.setData({
            total: total,
            minusStatus: minusStatus,
        })
        this.priceTotal()
    },
    /*点击加号*/
    bindPlus: function () {
        let total = this.data.total;
        let num = this.data.num;
        if (total < num) {
            total++;
        } else {
            wx.showToast({
                title: '商品库存不足',
                icon: 'none'
            })
            setTimeout(function () {
                wx.hideToast()
            }, 2000);
        }
        let minusStatus = total < num ? 'normal' : 'disable';
        this.setData({
            total: total,
            minusStatus: minusStatus
        });
        this.priceTotal();
    },
    /**
     * testarea事件
     */
    bindTextAreaBlur: function (e) {
        this.setData({
            remark: e.detail.value
        })
    },
    /**
     * 提交按钮
     */
    onSubmit() { 
        // 判断信息是否完整
        if(this.data.address) {
            this.setData({
                isShow: true
            });
            // <== 创建订单 ==>
            // 订单创建时间
            this.setData({
                createTime: new Date()
            });
        }else {
            this.$showMsg('请选择收货地址');
        }
    },
    /**
     * 支付成功
     * @param {*} e 
     */
    onToPay(e) {
        wx.showLoading({
            title: '支付中',
        });
        // 模拟支付
        let orderNum = this.produceOrder()
        // 存储数据库
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'addIdlemallOrder',
                reqData: {
                    address: this.data.address,         // 订单收货地址
                    goodsMess: this.data.goodsMess,     // 所购商品信息
                    itemNo: this.data.id,               // 商品编号-对应商品表的ID
                    createTime: this.data.createTime,   // 订单创建时间
                    payment: this.data.price,           // 订单实付金额
                    payTime: new Date(),                // 订单支付时间
                    amount: this.data.total,            // 所购商品数量
                    orderStatus: 1,                     // 订单状态：0-待付款，1-待发货，2-已发货，3-售后中，4-已完成，
                    orderDetail: this.data.remark,      // 订单备注
                    orderCode: orderNum,                // 订单号 
                }
            }
        }).then(res => {
            // 添加订单成功
            // console.log('add order success ==>', res);
            this.data.orderId = res.result.resData._id;
            // 添加消息
            this.addGoodsMess(res.result.resData._id, this.data.goodsMess.goodsData.goodsName, 1);
            // 更新数据库库存
            let num = this.data.num - this.data.total;
            if(num === 0) {
                this.setData({
                    status: '无库存'
                });
            }
            return db.collection('idlemallSend').doc(this.data.id).update({
                data: {
                    goodsStatus: this.data.status,
                    ['goodsData.goodsNum']: num
                }
            });
        }, err => {
            console.log('add order error ==>', err);
        }).then(res => {
            // console.log('update send success ==>', res);
            // 修改成功，隐藏加载框
            return wx.hideLoading();  
        }, err => {
            console.log('update send error ==>', err);
        }).then(res => {
            this.$showMsg('支付成功', 'success');
            // 跳转页面后清除本地存储数据
            this.deleteRStroge();
            wx.redirectTo({
              url: '../buySuccess/buySeccess?id=' + this.data.orderId + '&type=已支付',
            });
        }, err => {
            console.log('nav to buySuccess error ==>', err);
        }).finally(() => {
            // 关闭支付框
            this.setData({
                isShow: false
            });
        });
    },
    /**
     * 取消支付
     * @param {*} e 
     */
    onCancelPay(e) {
        // 取消支付
        if(!e.detail) {
            wx.showLoading({
                title: '订单创建中',
            });
            let orderNum = this.produceOrder()
            // 存储数据库
            wx.cloud.callFunction({
                name: 'databaseApi',
                data: {
                    type: 'addIdlemallOrder',
                    reqData: {
                        address: this.data.address, // 订单收货地址
                        goodsMess: this.data.goodsMess, // 所购商品信息
                        itemNo: this.data.id, // 商品编号-对应商品表的ID
                        createTime: this.data.createTime, // 订单创建时间
                        payment: this.data.price, // 订单实付金额
                        payTime: '', // 订单支付时间
                        amount: this.data.total, // 所购商品数量
                        orderStatus: 0, // 订单状态：0-待付款，1-待发货，2-已发货，3-售后中，4-已完成，
                        orderDetail: this.data.remark, // 订单备注
                        orderCode: orderNum, // 订单号 
                    }
                }
            }).then(res => {
                // 添加订单成功
                // console.log('add order success ==>', res);
                this.data.orderId = res.result.resData._id;
                // 添加消息
                // this.addGoodsMess(res.result.resData._id, this.data.goodsMess.goodsData.goodsName, 0);

                // 更新数据库库存
                let num = this.data.num - this.data.total;
                if (num === 0) {
                    this.setData({
                        status: '无库存'
                    });
                }
                return db.collection('idlemallSend').doc(this.data.id).update({
                    data: {
                        goodsStatus: this.data.status,
                        ['goodsData.goodsNum']: num
                    }
                });
            }, err => {
                console.log('add order error ==>', err);
            }).then(res => {
                // console.log('update send success ==>', res);
                // 修改成功，隐藏加载框
                return wx.hideLoading();
            }, err => {
                console.log('update send error ==>', err);
            }).then(res => {
                this.$showMsg('订单创建成功', 'success');
                // 跳转页面后清除本地存储数据
                this.deleteRStroge();
                wx.redirectTo({
                    url: '../buySuccess/buySeccess?id=' + this.data.orderId + '&type=未支付',
                });
            }, err => {
                console.log('nav to buySuccess error ==>', err);
            });
        }
    },
    /**
     * 随机生成订单号函数
     */
    produceOrder() {
        //配送以PS开头,自提用ZT开头
        let way = this.data.goodsMess.goodsData.goodsWay
        let orderArr = 'P'
        if (way === '自提') {
            orderArr = 'Z'
        }
        return utils.orderCode(orderArr);
    },
    /**
     * 添加消息
     * @param {*} orderId 
     * @param {*} goodsName 
     * @param {*} state 
     */
    addGoodsMess(orderId, goodsName, state) {
        // 添加消息
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'addGoodsMess',
                reqData: {
                    orderId: orderId,
                    goodsName: goodsName,
                    state: state
                }
            }
        });
    },
    /**
     * 更新商品的数据库
     */
    updataSend() {
        let num = this.data.num - this.data.total;
        let index = 'goodsNum'; //更新goodsData中的goodsNum
        if (num === 0) {
            this.setData({
                status: '无库存'
            });
        }
        db.collection("idlemallSend").doc(this.data.id).update({
            data: {
                goodsStatus: this.data.status,
                ['goodsData.' + [index]]: num
            },
            success: res => {
                wx.navigateTo({
                    url: '../buySuccess/buySeccess?id=' + this.data.orderId + '&buyerId=' + this.data.id,
                })
            },
            fail: err => {
                console.log(err)
            }
        }).then(res => {
            console.log('update send success ==>', res);
            // 跳转
        }, err => {
            console.log('update send error ==>', err);
        });
    },
    deleteRStroge() {
        wx.removeStorageSync('idlemallID');
        wx.removeStorageSync('idlemallAddress');
    },
    /**
     * 获取滚动视图高
     */
    getScrollHeight() {
        this.setData({
            scrollHeight: wx.getSystemInfoSync().windowHeight - 100
        });
    },
    /**
     * 显示消息
     */
    $showMsg(msg, type = 'none') {
        wx.showToast({
          title: msg,
          icon: type
        });
    },
})